import {useCallback, useRef, useState} from 'react';
import {Alert} from 'react-native';

interface PageParams {
    pageNo: number;
    pageSize: number;
}

// API函数的类型定义，它接收分页参数，并返回一个Promise
// Promise的解析值应包含一个名为list的数组
type ApiFunction<T> = (params: PageParams) =>
    Promise<{ data: { list: T[], total: number } }>;

/**
 * @钩子 useList
 * @功能描述 封装列表的通用逻辑
 * @param apiFunc - 一个返回Promise的API函数，用于获取数据
 * @param pageSize - 每页的项目数
 * @returns 列表状态、加载状态和操作函数
 */
export function useList<T>(apiFunc: ApiFunction<T>, pageSize: number = 10) {
    const [list, setList] = useState<T[]>([]);
    const [isRefreshing, setIsRefreshing] = useState<boolean>(false);

    // 使用ref来存储状态，避免useCallback的依赖问题
    const stateRef = useRef({
        pageNo: 0,
        loading: false,
        hasMore: true,
    });

    const loadData = useCallback(async (isRefresh: boolean) => {
        if (stateRef.current.loading || (!isRefresh && !stateRef.current.hasMore)) {
            return;
        }

        stateRef.current.loading = true;
        if (isRefresh) {
            setIsRefreshing(true);
        }

        const targetPage = isRefresh ? 1 : stateRef.current.pageNo + 1;

        try {
            const res = await apiFunc({pageNo: targetPage, pageSize});
            const resData = res.data;
            const resList = resData.list || [];

            stateRef.current.hasMore = resList.length >= pageSize;

            if (isRefresh) {
                setList(resList);
            } else {
                setList(prev => [...prev, ...resList]);
            }
            stateRef.current.pageNo = targetPage;
        } catch (error) {
            Alert.alert('错误', '获取列表失败，请稍后重试');
        } finally {
            stateRef.current.loading = false;
            setIsRefreshing(false);
        }
    }, [apiFunc, pageSize]); // 依赖项现在是稳定的

    const refresh = useCallback(() => {
        stateRef.current.hasMore = true; // 重置hasMore状态
        loadData(true);
    }, [loadData]);

    const loadMore = useCallback(() => {
        loadData(false);
    }, [loadData]);

    return {
        list,
        // loading 和 isRefreshing 仍然作为 state 返回，以便UI可以响应它们的变化
        loading: stateRef.current.loading,
        isRefreshing,
        hasMore: stateRef.current.hasMore,
        refresh,
        loadMore,
    };
}